﻿using System;
using System.IO;
using System.Windows.Forms;
using CloudShot.Core.Interfaces;
using CloudShot.Core.Utils;

namespace CloudShot.ImageStorages
{
	//TODO REFACTOR
	public partial class FileSystemStorageSettingsControl : UserControl, ISettingsUIHolder
	{
		private readonly FileSystemStorage _storage;

		public FileSystemStorageSettingsControl(FileSystemStorage storage)
		{
			_storage = storage;
			InitializeComponent();
		}

		private void OnBrowseClick(object sender, EventArgs e)
		{
			var dialog = new FolderBrowserDialog();
			dialog.Description = "Select folder to save screenshots";

			if (!string.IsNullOrEmpty(txtPath.Text))
				dialog.SelectedPath = txtPath.Text;

			if (dialog.ShowDialog() == DialogResult.OK)
			{
				txtPath.Text = dialog.SelectedPath;
				txtPath.SelectionStart = txtPath.Text.Length;
				toolTip.SetToolTip(txtPath, txtPath.Text);
			}

			//BrowseToFolder("dddd", DropboxUtils.DropboxPublicFolder);
		}

		public IImageStorage Storage
		{
			get { return _storage; }
		}

		public Control Control { get { return this; } }

	    public void LoadSettings()
	    {
            cboImageFormat.Items.Clear();

            foreach (string extension in _storage.SupportedFormats.GetImageExtensions())
            {
                cboImageFormat.Items.Add(extension);
            }

	        cboImageFormat.SelectedItem = _storage.CurrentImageFormat.GetImageExtension();

	        txtPath.Text = _storage.FolderToSave;
            txtPath.SelectionStart = txtPath.Text.Length;
            toolTip.SetToolTip(txtPath, txtPath.Text);
	    }

	    public bool ValidateSettings()
		{
			//TODO по идее надо делать такую же проверку при шоте
			try
			{
				Directory.CreateDirectory(txtPath.Text);//TODO плохо создавать папку в методе Validate!!!
			}
			catch (Exception err)
			{
				string message = string.Format("Invalid path to save.\n{0}\nPlease enter correct path.", err.Message);
				MessageBox.Show(message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
				txtPath.Focus();
				return false;
			}

			return true;
		}

	    public void SaveSettings()
	    {
            _storage.CurrentImageFormat = ImageTypeUtils.GetImageType((string)cboImageFormat.SelectedItem);
	        _storage.FolderToSave = txtPath.Text;
	    }

	    public void ClearUnsavedSettings()
	    {
	    }
	}
}